using System;
using Microsoft.Extensions.DependencyInjection;

namespace AutomaticSubtitles.Service.Infrastructure.Helper;

/// <summary>
/// 依赖解析器
/// </summary>
public static class DependencyResolver
{
    private static IServiceProvider _serviceProvider;

    /// <summary>
    /// 获取服务提供者
    /// </summary>
    public static IServiceProvider ServiceProvider => _serviceProvider;

    /// <summary>
    /// 初始化依赖解析器
    /// </summary>
    /// <param name="serviceProvider">服务提供者</param>
    public static void Initialize(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// 解析指定类型的服务
    /// </summary>
    /// <typeparam name="T">服务类型</typeparam>
    /// <returns>服务实例</returns>
    public static T Resolve<T>() where T : class
    {
        if (_serviceProvider == null)
        {
            throw new InvalidOperationException("DependencyResolver尚未初始化。请先调用Initialize方法。");
        }

        return _serviceProvider.GetRequiredService<T>();
    }

    /// <summary>
    /// 解析指定类型的服务
    /// </summary>
    /// <param name="serviceType">服务类型</param>
    /// <returns>服务实例</returns>
    public static object Resolve(Type serviceType)
    {
        if (_serviceProvider == null)
        {
            throw new InvalidOperationException("DependencyResolver尚未初始化。请先调用Initialize方法。");
        }

        return _serviceProvider.GetRequiredService(serviceType);
    }
}